const Koa = require('koa');

const { resolve } = require('path')

const { koaBody } = require('koa-body')  // 请求数据解析器
const logger = require('koa-logger')  // 请求记录器
const koaStatic = require('koa-static')  // 静态文件服务中间件
const view = require('koa-views')  // 模板呈现中间件
const router = require('./router/index')  // 路由
const moment = require('moment')  // 时间格式转换
const cors = require('koa2-cors')  // 跨域

const app = new Koa();

app.use(koaBody(
  {
    enableTypes: ['json', 'form', 'text'],
    multipart: true, // 是否支持 multipart-formdate 的表单
    formidable: {
      //上传文件存储目录
      uploadDir: resolve(__dirname, '../public/upload'),
      //允许保留后缀名
      keepExtensions: true,
      multipart: true,
    }
  }
))
  .use(cors())
  .use(logger())
  .use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    const currentTime = moment().format('YYYY:MM:DD HH:mm:ss')
    console.log(`--> log: ${ctx.method} - ${ctx.url} - ${ms}ms 时间: ${currentTime}`)
  })
  .use(koaStatic(resolve(__dirname, '../public/upload')))
  .use(view(resolve(__dirname, './views/'),
    { extension: 'html' },
  ))
  .use(router.routes())
  .use(router.allowedMethods())

module.exports = app;